package com.jjc.android.activity

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.InputType
import android.view.Gravity
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.allen.library.SuperButton
import com.github.gzuliyujiang.wheelpicker.DatePicker
import com.github.gzuliyujiang.wheelpicker.entity.DateEntity
import com.google.gson.reflect.TypeToken
import com.hjq.toast.ToastUtils
import com.jjc.android.Constants
import com.jjc.android.R
import com.jjc.android.UserManager
import com.jjc.android.base.BaseActivity
import com.jjc.android.dialog.AttachListDialog
import com.jjc.android.dialog.BottomWheelDialog
import com.jjc.android.dialog.MessageImageDialog
import com.jjc.android.entity.*
import com.jjc.android.net.SimpleHttpCallback
import com.jjc.android.util.AndroidBug5497Workaround
import com.jjc.android.util.Common
import com.jjc.android.util.Common.parseInt
import com.jjc.android.util.Convert
import com.jjc.android.util.InputFilterMinMax
import com.jjc.android.util.MultiLanguageUtil
import com.jjc.android.util.messenger.ActivityMessenger
import com.jjc.android.util.paramEx
import com.jjc.android.view.CommonKt
import com.jjc.android.view.CommonKt.genderParse
import com.jjc.android.view.formatTwo
import com.jjc.android.view.hide
import com.jjc.android.view.layout.*
import com.jjc.android.view.onClick
import com.jjc.android.view.textChange
import com.lzy.okgo.OkGo
import com.xw.repo.XEditText
import org.greenrobot.eventbus.EventBus
import kotlin.properties.Delegates

class FillProductInfoActivity : BaseActivity(){

    companion object{
        fun start(context: Activity,scanInfo:ScanCardDto,testerId:String?,deviceSn:String, action:(DetectionInfo)->Unit){
            val intent = Intent(context,FillProductInfoActivity::class.java)
            intent.putExtra(Constants.BUNDLE_INFO,scanInfo)
            intent.putExtra("testerId",testerId)
            intent.putExtra("deviceSn",deviceSn)
            ActivityMessenger.startActivityForResult(context,intent){
                (it?.getSerializableExtra(Constants.BUNDLE_INFO) as? DetectionInfo)?.let(action)
            }
        }
    }

    override val layoutId: Int = R.layout.activity_fill_product_info
    private val okBtn: SuperButton by lazy { findViewById<SuperButton>(R.id.okBtn) }
    private val weightEt: XEditText by lazy { findViewById<XEditText>(R.id.weightEt) }
    private val tallEt: XEditText by lazy { findViewById<XEditText>(R.id.tallEt) }
    private val chooseBirthDayBtn: TextView by lazy { findViewById<TextView>(R.id.chooseBirthDayBtn) }
    private val chooseGenderBtn: TextView by lazy { findViewById<TextView>(R.id.chooseGenderBtn) }
    private val nameEt: XEditText by lazy { findViewById(R.id.nameEt) }
    private val productNameTxt: TextView by lazy { findViewById<TextView>(R.id.productNameTxt) }
    private val homeBtn: ImageView by lazy { findViewById<ImageView>(R.id.homeBtn) }
    private val chooseTesterBtn:View by lazy { findViewById(R.id.chooseTesterBtn) }
    private val extroFillLayout:LinearLayout by lazy { findViewById(R.id.extroFillLayout) }
    private var scanDeviceDto:ScanCardDto? = null
    private var testerId:String? = null
    private var deviceSn:String = ""

    override fun initView(savedInstanceState: Bundle?) {
        setActivityTitle(getString(R.string.tester_and_info_txt))
        AndroidBug5497Workaround.assistActivity(this)
        homeBtn.visibility = View.VISIBLE
        homeBtn.onClick {
            MessageImageDialog.Builder(this)
                .imageResId(R.mipmap.alert_jiancejindu_pic)
                .content(getString(R.string.dete_not_save_txt))
                .okClick {
                    MainActivity.start(this)
                }
                .build()
                .show()
        }
        tallEt.filters = arrayOf(InputFilterMinMax(0f,250f))
        weightEt.filters = arrayOf(InputFilterMinMax(0f,400f))
        chooseTesterBtn.onClick {
            AttachListDialog<TestedPersonDto>(chooseTesterBtn)
                .contentList(testedPersonList)
                .onItemClick { _, value ->
                    if(value == addTesterMode){
                        AddTestedPersonActivity.start(this){
                            fetchTesters(it)
                        }
                    }else{
                        currentTester = value
                    }
                }
                .build()
                .show()
        }
        okBtn.onClick {
            submit()
        }
        chooseGenderBtn.onClick {
            genderDialog.show()
        }
        chooseBirthDayBtn.onClick {
            birthdayPicker.show()
        }
        val action:(String)->Unit = {
            checkBtnEnable()
        }
        nameEt.textChange(action = action)
        weightEt.textChange(action = action)
        tallEt.textChange(action = action)
        fetchPageInfo()
    }

    private fun checkBtnEnable(){
        okBtn.isEnabled = true
    }

    private fun submit(){
        if(nameEt.textEx.isNullOrEmpty()){
            ToastUtils.show(getString(R.string.input_test_name))
            return
        }
        if(chooseGenderBtn.text.isNullOrEmpty()){
            ToastUtils.show(getString(R.string.choose_gender))
            return
        }
        if(chooseBirthDayBtn.text.isNullOrEmpty()){
            ToastUtils.show(getString(R.string.choose_birth_txt))
            return
        }
        if(tallEt.textEx.isNullOrEmpty()){
            ToastUtils.show(getString(R.string.input_tester_tall_txt))
            return
        }
        if(weightEt.textEx.isNullOrEmpty()){
            ToastUtils.show(getString(R.string.input_weight_txt))
            return
        }
        if(!fillExtraList.isNullOrEmpty()){
            fillExtraList.forEach { target->
                if(target.second.visibility == View.VISIBLE &&target.second.text.isNullOrEmpty()){
                    ToastUtils.show(target.first.prompt)
                    return
                }
            }
        }
        showLoadingDialog()
        modifyTester{testerId->
            if(!testerId.isNullOrEmpty()){
                val detectionInfo = DetectionInfo().apply {
                    scanDeviceDto?.lcq6twxkuyytwpkc?.let {
                        if(!it.isNullOrEmpty()){
                            val info = it[0]
                            minorTermId = info.id

                        }
                    }
                    minorTermName = scanDeviceDto?.jsonMember4arvpt0ckfechc6h
                    minorTermEnglishName = scanDeviceDto?.d5zyxqmhtbzruvz6
                    detectionUserId = testerId
                    detectionUserName = nameEt.textEx
                    gender = chooseGenderBtn.text.toString().genderParse(true)
                    birthday = chooseBirthDayBtn.text.toString()
                    age = Common.getAge(chooseBirthDayBtn.text.toString()).toString()
                    height = tallEt.textEx.parseInt()
                    weight = weightEt.textEx.parseInt()
                    exInputs = ArrayList<KeyValuePair>().also {
                        it.addAll(fillExtraList.filter { it.second.visibility == View.VISIBLE }.map { pair->
                            KeyValuePair(pair.first.fieldName,pair.second.text.toString())
                        })
                    }
                    deviceId = deviceSn
                    stickerId = scanDeviceDto?.tkynuu9ecdit0llv
                    waitTime = scanDeviceDto?.danmoe2hn6ie3yqu.parseInt()
                    measLowEnd = scanDeviceDto?.v6qpfu0mxss3cw1t.parseInt()
                    measHighEnd = scanDeviceDto?.wn3d1qkftirpidef.parseInt()
                    measUnit = scanDeviceDto?.n7cplrqzmakiyazi
                    volumeUnit = scanDeviceDto?.jsonMember3ntlcnyxsmlzs1w0
                }

                setResult(Activity.RESULT_OK, Intent().apply {
                    putExtra(Constants.BUNDLE_INFO,detectionInfo)
                })
                finish()
            }else{
                hideLoadingDialog()
            }
        }
    }


    private fun modifyTester(action:(String?)->Unit){
        if(currentTester==null){
            OkGo.post<LzyResponse<IdValuePair>>(Constants.addFormRow)
                .paramEx(mutableMapOf(
                    "formheaduuid" to "83ed64e98f6c4edbaf7b388d7691e57b",
                    "fields" to mapOf<String,Any?>("61xugqtzoyid5pw2" to UserManager.userId(),
                        "8pa55qzbspju5tzn" to nameEt.textEx,
                        "cu8thtdjxhfbxpjx" to tallEt.textEx,
                        "kpurkwtmvsd9lqui" to chooseGenderBtn.text.toString().genderParse(true),
                        "orldw605kccdju8z" to chooseBirthDayBtn.text.toString(),
                        "yzqfbls6zzqh9tyl" to weightEt.textEx)
                ),true)
                .tag(this@FillProductInfoActivity)
                .execute(object : SimpleHttpCallback<LzyResponse<IdValuePair>>(){
                    override fun onCallSuccess(response: LzyResponse<IdValuePair>) {
                        EventBus.getDefault().post(ChangeTesterEvent())
                        action.invoke(response.data?.id)
                    }

                    override fun onCallError(error: String?) {
                        super.onCallError(error)
                        action.invoke(null)
                    }
                })
        }else{
            OkGo.post<LzyResponse<Any>>(Constants.editFormRowById)
                .paramEx(mutableMapOf(
                    "formheaduuid" to "83ed64e98f6c4edbaf7b388d7691e57b",
                    "rowid" to currentTester?.id,
                    "fields" to mapOf<String,Any?>(
                        "8pa55qzbspju5tzn" to nameEt.textEx,
                        "cu8thtdjxhfbxpjx" to tallEt.textEx,
                        "kpurkwtmvsd9lqui" to chooseGenderBtn.text.toString().genderParse(true),
                        "orldw605kccdju8z" to chooseBirthDayBtn.text.toString(),
                        "yzqfbls6zzqh9tyl" to weightEt.textEx)
                ),true)
                .tag(this@FillProductInfoActivity)
                .execute(object : SimpleHttpCallback<LzyResponse<Any>>(){
                    override fun onCallSuccess(response: LzyResponse<Any>) {
                        EventBus.getDefault().post(ChangeTesterEvent())
                        action.invoke(currentTester?.id)
                    }

                    override fun onCallError(error: String?) {
                        super.onCallError(error)
                        action.invoke(null)
                    }

                })
        }
    }
    private val fillExtraList:ArrayList<Pair<DetectionFillInfo,TextView>> = ArrayList()
    private fun createFillLayout(data:List<DetectionFillInfo>?){
        extroFillLayout.removeAllViews()
        fillExtraList.clear()
        if(data.isNullOrEmpty()) return
        data.forEach {info->
            extroFillLayout.LinearLayout {
                layout_width = match_parent
                layout_height = 50
                margin_top = 15
                padding_start_end = 15
                background_res = R.drawable.shape_et_bg
                TextView {
                    layout_width = wrap_content
                    layout_height = wrap_content
                    layout_gravity = Gravity.CENTER_VERTICAL
                    textStyle = bold
                    textSize = 16f
                    textColorRes = R.color.c_333333
                    text = info.fieldTxt
                }
                if(info.fieldType == Constants.FieldType.SELECT){
                    TextView {
                        layout_width = 0
                        layout_height = match_parent
                        weight = 1f
                        gravity = gravity_right or gravity_center_vertical
                        drawable_padding = 15
                        drawable_end = R.mipmap.tuya_nav_icon_down
                        hint = info.prompt
                        textColorRes = R.color.c_333333
                        setHintTextColor(getColor(R.color.c_999999))
                        textSize = 16f
                        margin_start = 15
                        onClick {
                            clickSelect(info,this)
                        }
                        fillExtraList.add(Pair(info,this))
                    }
                }else{
                    XEditText{
                        layout_width = 0
                        layout_height = match_parent
                        weight = 1f
                        gravity = gravity_right or gravity_center_vertical
                        drawable_padding = 15
                        drawable_end = R.mipmap.tuya_nav_icon_down
                        hint = info.prompt
                        textColorRes = R.color.c_333333
                        setHintTextColor(getColor(R.color.c_999999))
                        textSize = 16f
                        margin_start = 15
                        background_res = 0
                        inputType = if(info.fieldType == Constants.FieldType.NUMBER) (InputType.TYPE_CLASS_NUMBER or InputType.TYPE_NUMBER_FLAG_DECIMAL or InputType.TYPE_NUMBER_FLAG_SIGNED) else InputType.TYPE_CLASS_TEXT
                        textChange {
                            checkBtnEnable()
                        }
                        fillExtraList.add(Pair(info,this))
                    }
                }
                if(info.fieldName=="sampleVolume"){
                    visibility = View.GONE
                }
            }
        }
    }

    private fun clickSelect(info:DetectionFillInfo,textView:TextView){
        if(info.options.isNullOrEmpty()) return
        BottomWheelDialog<String>(this@FillProductInfoActivity)
            .title(info.prompt)
            .contentList(info.options)
            .onItemClick { _, value ->
                clickSelectItem(textView,value)
            }
            .build()
            .show()
    }

    private fun clickSelectItem(textView:TextView,value:String){
        textView.text = value
        fillExtraList.find {
            it.first.fieldName=="sampleVolume"
        }?.let { pair->
            if(value.contains("24")){
                (pair.second.parent as? View)?.visibility = View.VISIBLE
                pair.second.visibility = View.VISIBLE
            }else{
                (pair.second.parent as? View)?.visibility = View.GONE
                pair.second.visibility = View.GONE
            }
        }
        checkBtnEnable()
    }

    private val genderDialog by lazy {
        BottomWheelDialog<KeyValuePair>(this)
            .title(getString(R.string.choose_gender_txt))
            .contentList(listOf(
                KeyValuePair(Constants.Gender_Woman, getString(R.string.woman_txt)),
                KeyValuePair(Constants.Gender_Man, getString(R.string.man_txt))
            ))
            .onItemClick { position, value ->
                chooseGenderBtn.text = value.value
                checkBtnEnable()
            }
            .build()
    }

    private val birthdayPicker: DatePicker by lazy {
        val picker = DatePicker(this)
        picker.wheelLayout.setRange(DateEntity.yearOnFuture(-100), DateEntity.today())
        picker.setOnDatePickedListener { year, month, day ->
            chooseBirthDayBtn.text = String.format("%d-%s-%s", year, month.formatTwo(), day.formatTwo())
            checkBtnEnable()
        }
        picker
    }



    override fun fetchPageInfo() {
        fetchTesters()
        OkGo.post<LzyResponse<PageInfo<DetectionFillPageDto>>>(Constants.getFormList)
            .paramEx(mutableMapOf("page" to 1,"pagesize" to 1,"needpage" to 1,"formheaduuid" to "ded7b290da4641309118a69a18fc89b8","filters" to listOf<KeyValuePair>(
                KeyValuePair("tfilhnr91gkmekdd",scanDeviceDto?.lcq6twxkuyytwpkc.let { if(it.isNullOrEmpty()) "" else it[0].id}),
                KeyValuePair("yllmwtdxzftugo1h",MultiLanguageUtil.getInstance().getValue("7599b8c0-e0d2-45d2-aaee-ba9de5a349be","86249b3a-0a54-4602-9d49-d8deafc850a6"))
            )),true)
            .tag(this)
            .execute(object : SimpleHttpCallback<LzyResponse<PageInfo<DetectionFillPageDto>>>(){
                override fun onCallSuccess(response: LzyResponse<PageInfo<DetectionFillPageDto>>) {
                    createFillLayout(response.data?.data?.let {
                        if(it.isNullOrEmpty()){
                            null
                        }else{
                            it.first()
                        }
                    }?.also {
                        if(!it.tfilhnr91gkmekdd.isNullOrEmpty()){
                            productNameTxt.text = it.tfilhnr91gkmekdd[0].value
                        }
                    }?.e5tlqxpbrortyd6x?.let {
                        try {
                            Convert.fromJson<List<DetectionFillInfo>>(it,object : TypeToken<List<DetectionFillInfo>>(){}.type)
                        }catch (e:Exception){
                            null
                        }
                    })
                    handleDefault()
                }
            })
    }

    private fun handleDefault(){
        if(!fillExtraList.isNullOrEmpty()){
            fillExtraList.forEachIndexed { index, pair ->
                if(pair.first.fieldType == Constants.FieldType.SELECT){
                    pair.first.options.forEachIndexed { childIndex, s ->
                        if(!s.isNullOrEmpty()&&s.contains("24")){
                            clickSelectItem(pair.second,s)
                            return
                        }
                    }
                }
            }
        }
    }
    private val addTesterMode: TestedPersonDto by lazy {
        TestedPersonDto().apply {
            jsonMember8pa55qzbspju5tzn = getString(R.string.newly_add_txt)
            id = "-1"
        }
    }
    private val testedPersonList = ArrayList<TestedPersonDto>()
    private var currentTester:TestedPersonDto? by Delegates.observable(null){ _, old, new->
        if(new==null){
            nameEt.setText("")
        }else{
            nameEt.setText(new.provideText())
            chooseGenderBtn.text = new.kpurkwtmvsd9lqui.genderParse(false)
            chooseBirthDayBtn.text = new.orldw605kccdju8z.let { if(it.isNullOrEmpty()) "" else if(it.length>10) it.substring(0,10) else it }
            tallEt.setText(new.cu8thtdjxhfbxpjx)
            weightEt.setText(new.yzqfbls6zzqh9tyl)
        }
    }
    private fun fetchTesters(targetId:String? = null){
        OkGo.post<LzyResponse<PageInfo<TestedPersonDto>>>(Constants.getFormList)
            .paramEx(mutableMapOf("page" to 1,"pagesize" to 100,"needpage" to 0,"formheaduuid" to "83ed64e98f6c4edbaf7b388d7691e57b","filters" to listOf<KeyValuePair>(
                KeyValuePair("61xugqtzoyid5pw2",UserManager.userId())
            )),true)
            .tag(this)
            .execute(object : SimpleHttpCallback<LzyResponse<PageInfo<TestedPersonDto>>>(false){
                override fun onCallSuccess(response: LzyResponse<PageInfo<TestedPersonDto>>) {
                    response.data?.data?.let {
                        testedPersonList.clear()
                        testedPersonList.addAll(it)
                        testedPersonList.add(addTesterMode)
                    }
                    val testerId = if(targetId.isNullOrEmpty()) testerId else targetId
                    if(!testedPersonList.isNullOrEmpty()&&testedPersonList.size>1){
                        currentTester = if(testerId.isNullOrEmpty()){
                            testedPersonList[0]
                        }else{
                            testedPersonList.find { it.id == testerId }
                        }
                        chooseTesterBtn.visibility = View.VISIBLE
                    }else{
                        chooseTesterBtn.visibility = View.GONE
                    }
                }

                override fun onCallError(error: String?) {
                    super.onCallError(error)
                }
            })
    }



    override fun setupArguments(args: Bundle?) {
        scanDeviceDto = args?.getSerializable(Constants.BUNDLE_INFO) as? ScanCardDto
        testerId = args?.getString("testerId")
        deviceSn = args?.getString("deviceSn")?:""
    }
}